package com.moore.service.Impl;

import com.moore.bean.Apartment;
import com.moore.bean.BaseEntity;
import com.moore.dto.ResponseData;
import com.moore.mapper.EntitiesMapper;
import com.moore.service.EntitiesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.moore.utils.Logger.toLog;

@Service
public class EntitiesServiceImpl implements EntitiesService {
    @Autowired
    private EntitiesMapper entitiesMapper;

    /**
     * 通用删除方法，根据实体类型进行删除
     * @param entities 要删除的实体列表
     * @param entityType 实体类型
     * @param status 实体需要修改的状态
     * @return 包含删除结果的响应信息
     */
    @Override
    @Transactional
    public ResponseData deleteEntities(List<? extends BaseEntity> entities, String entityType, String status) {
        List<Long> idsToDelete = new ArrayList<>();
        List<String> namesToDelete = new ArrayList<>();
        StringBuilder outputMessage = new StringBuilder();

        System.out.println(entities.toString());

        if ("room_number".equals(entityType)) {
            entities.forEach(entity -> {
                if (entity instanceof Apartment) entity.setName(((Apartment) entity).getRoomNumber());
            });
        }

        String type;
        switch (entityType) {
            case "area_name" : type = "区域"; break;
            case "community_name" : type = "小区"; break;
            case "room_number" : type = "套房"; break;
            default: throw new IllegalStateException("Unexpected value: " + entityType);
        }

        // 根据实体类型获取租赁公寓的计数
        List<Map<String, Object>> results = entitiesMapper.leaseEntitiesCount(entities, entityType);
        System.out.println(results.toString());

        // 遍历查询结果，判断是否可以删除
        for (Map<String, Object> result : results) {
            String name = (String) result.get(entityType);
            Long count = (Long) result.get("count");
            System.out.println("name: " + name + " count: " + count);
            BaseEntity matchingEntity = entities.stream()
                    .filter(entity -> entity.getName().equals(name))
                    .findFirst()
                    .orElse(null);
            if (matchingEntity != null) {
                if (count == 0) {
                    System.out.println(1111111111);
                    idsToDelete.add(matchingEntity.getId());
                    namesToDelete.add(name);
                    outputMessage.append(type).append(" ").append(name).append(" ").append(status).append("成功\n");
                } else {
                    System.out.println(222222222);
                    if ("room_number".equals(entityType)) outputMessage.append(type).append(" ").append(name)
                                .append("已被被租赁，无法").append(status).append("\n");
                    else outputMessage.append(type).append(" ").append(name)
                                .append(" 有 ").append(count).append(" 套套房被租赁，无法").append(status).append("\n");

                }
            }
        }
        System.out.println(33333333);
        // 记录日志
        if (outputMessage.length() > 0) toLog(outputMessage.toString());
        System.out.println(444444444);
        // 如果有可以删除的实体，执行删除操作
        if (!idsToDelete.isEmpty()) {
            List<Map<String, Object>> deleteEntities = new ArrayList<>();
            String newType;
            switch (entityType) {
                case "area_name" : newType = "area"; break;
                case "community_name" : newType = "community"; break;
                case "room_number" : newType = "apartment"; break;
                default: throw new IllegalStateException("Unexpected value: " + entityType);
            }

            // 删除主实体（区域，小区，套房）
            Map<String, Object> entityMap = new HashMap<>();
            entityMap.put("table", newType);
            entityMap.put("column", "id");
            entityMap.put("status", status);
            entityMap.put("values", idsToDelete);
            entitiesMapper.deleteEntity(entityMap);

            // 若为区域，还要删除相关的小区
            if ("area_name".equals(entityType)) {
                Map<String, Object> communityMap = new HashMap<>();
                communityMap.put("table", "community");
                communityMap.put("column", "area");
                communityMap.put("status", status);
                communityMap.put("values", namesToDelete);
                entitiesMapper.deleteEntity(communityMap);
            }

            // 若为区域或小区，还要删除相关的套房
            if (!"room_number".equals(entityType)) {
                Map<String, Object> apartmentMap = new HashMap<>();
                apartmentMap.put("table", "apartment");
                apartmentMap.put("column", entityType);
                apartmentMap.put("status", status);
                apartmentMap.put("values", namesToDelete);
                entitiesMapper.deleteEntity(apartmentMap);
            }
        }

        return new ResponseData(200, outputMessage.toString(), null, idsToDelete.size());
    }
}
